package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("ordersetting")
public class OrderSettingController {
    @Reference
    private OrderSettingService orderSettingService;

    /**
     *上传文件
     * @param file
     * @return
     */
    @RequestMapping("importOrderSettings")
    public Result importOrderSettings(@RequestParam("excelFile")MultipartFile file){

        try {
            //利用工具类读取Excel,list中的每一行数据
            List<String[]> list = POIUtils.readExcel(file);

            //判断集合是否为空,防止上传了一个空的excel
            if(list!=null){

                //定义一个list来存放OrderSetting
                List<OrderSetting> orderSettings = new ArrayList<>();

                //遍历模板的每一个String[]将里面的数据全部封装到一个个的ordersetting对象中
                //再将ordersetting对象封装到list集合中,方便service传递和获取数据
                for (String[] strings : list) {

                    //创建一个新的ordersetting实例对象
                    OrderSetting orderSetting = new OrderSetting();
                    orderSetting.setOrderDate(DateUtils.parseString2Date(strings[0],"yyyy/MM/dd"));
                    orderSetting.setNumber(Integer.parseInt(strings[1]));
                    orderSettings.add(orderSetting);
                }
                orderSettingService.importOrderSettings(orderSettings);

            }

            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }

    }

    @RequestMapping("findOrderSettingByMonth")
    public Result findOrderSettingByMonth(@RequestParam("date")String date){

        try {
            List<Map> list = orderSettingService.findOrderSettingByMonth(date);
            return new Result(true,MessageConstant.QUERY_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDERSETTING_FAIL);
        }

    }

}
